#!/bin/bash

set -ex

# 配置参数
INSTALL_PREFIX="./out"      # 安装目录
BUILD_DIR="./build"         # 构建目录
PORT=50051                  # 服务端端口
CLIENT_EXE="${INSTALL_PREFIX}/bin/client"
BUILD_TYPE="MinSizeRel"

# 检查是否连接了Android设备
check_android_device() {
    # 检查 adb 是否可用
    if ! command -v adb &> /dev/null; then
        echo "Error: adb 命令未找到，请确保已配置 Android SDK"
        exit 1
    fi

    # 检查设备连接状态（排除 unauthorized 等无效状态）
    local device_status
    device_status=$(adb devices | awk '/device$/ {print $2}')

    if [ -z "$device_status" ]; then
        echo "Error: 未检测到已连接的 Android 设备"
        echo "提示：请确保设备已开启 USB 调试并授权当前电脑"
        exit 1
    fi
}

# 清理函数：停止服务端并清理临时文件
cleanup() {
    # 停止安卓应用
    adb shell am force-stop com.example.grpcapp

    echo "Cleanup complete."
    exit 0
}

# 捕获中断信号，执行清理
trap cleanup SIGINT SIGTERM

# 构建项目
build_project() {
    echo "Building project..."

    # 运行CMake配置
    cmake -S . -B build -G "Ninja"                  \
        -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}    \
        -DCMAKE_BUILD_TYPE=${BUILD_TYPE}            \
        -DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE        \
        -DCMAKE_C_COMPILER=clang                    \
        -DCMAKE_CXX_COMPILER=clang++

    # 构建项目
    cmake --build build --config ${BUILD_TYPE} -j$(nproc)

    # 安装到指定目录
    echo "Installing to ${INSTALL_PREFIX}..."
    cmake --install build --config ${BUILD_TYPE}
}

# 启动服务端
start_android_server() {
    echo "Build and install Android server..."
    cd platforms/android && ./gradlew assembleRelease && cd ../../

    # 创建端口映射
    adb forward tcp:${PORT} tcp:${PORT}

    # 启动安卓应用
    adb shell am start -n com.example.grpcapp/com.example.grpcapp.MainActivity --es PORT "${PORT}"

    # 检查端口是否监听中
    while ! nc -z localhost ${PORT}; do
        echo "Waiting for server to start..."
        sleep 1
    done
}

# 运行客户端
run_client() {
    echo "Starting gRPC client..."
    if [ ! -f ${CLIENT_EXE} ]; then
        echo "Error: Client executable not found at ${CLIENT_EXE}"
        cleanup
        exit 1
    fi

    echo "Connecting to server at localhost:${PORT}..."
    ${CLIENT_EXE} localhost ${PORT}

    # 客户端退出后等待用户输入再关闭服务端
    echo -e "\nClient exited."
}

# 主流程
main() {
    echo "=== gRPC Auto Build & Run Script ==="
    check_android_device
    build_project
    start_android_server
    run_client
    cleanup
}

# 启动主流程
main
